class_name UI
extends CanvasLayer

const TEXTURE_AVATAR_MAP: Dictionary[EnemyData.EnemyType, CompressedTexture2D] = {
	EnemyData.EnemyType.PUNCK: preload("res://assets/art/ui/avatars/avatar-punk.png"),
	EnemyData.EnemyType.GOON: preload("res://assets/art/ui/avatars/avatar-goon.png"),
	EnemyData.EnemyType.THUG: preload("res://assets/art/ui/avatars/avatar-thug.png"),
	EnemyData.EnemyType.BOUNCER: preload("res://assets/art/ui/avatars/avatar-boss.png")
}

const PREFAB_OPTIONS_SCREEN: PackedScene = preload("res://scenes/ui/options_screen.tscn")
const PREFAB_DEATH_SCREEN: PackedScene = preload("res://scenes/ui/death_screen.tscn")
const PREFAB_GAME_OVER_SCREEN: PackedScene = preload("res://scenes/ui/game_over_screen.tscn")

enum Screen {
	OPTIONS_SCREEN,
	DEATH_SCREEN,
	GAME_OVER_SCREEN
}


@onready var playerAvatar: TextureRect = $UIContainer/PlayerAvatar
@onready var playerHealthBar: HealthBar = $UIContainer/PlayerAvatar/PlayerHealthBar
@onready var enemyAvatar: TextureRect = $UIContainer/EnemyAvatar
@onready var enemyHealthBar: HealthBar = $UIContainer/EnemyAvatar/EnemyHealthBar
@onready var comboIndicator: ComboIndicator = $UIContainer/ComboIndicator
@onready var scoreIndicator: ScoreIndicator = $UIContainer/ScoreIndicator
@onready var goIndicator: FlickeringTexutreRect = $UIContainer/GoIdicator
@onready var stageTransition: StageTransition = $UIContainer/StageTransition


## 敌人头像消失的间隔时间
@export var duration_enemy_avatar_hide: float = 1.0
## 玩家重生扣除的分数
@export var reborn_cost_score: int = 500
## 玩家初始的分数
@export var player_initial_score: int


var enemy_avatar_hide_time: float = 0.0
var options_screen: OptionsScreen = null
var death_screen: DeathScreen = null
var game_over_screen: GameOverScreen = null

var player: Player
var inputManager: InputManager


func _init():
	inputManager = InputManager.new()

	DamageManager.player_health_change.connect(on_player_health_change)
	DamageManager.enemy_health_change.connect(on_enemy_health_change)
	StageManager.checkpoint_complete.connect(on_checkpoint_complete)
	StageManager.player_dead.connect(on_player_dead)



func _ready():
	enemyAvatar.visible = false
	comboIndicator.combo_reset.connect(on_combo_reset)

	await get_tree().process_frame
	player = Helper.find_player(get_tree())

	if player_initial_score > 0:
		scoreIndicator.set_score(player_initial_score)



func _process(delta: float):
	process_input()
	update_enemy_avatar(delta)


func process_input():
	if death_screen and inputManager.accept_input():
		if can_reborn():
			close_death_screen()
			player_reborn()
		return

	if not inputManager.menu_input():
		return
	display_options_screen()



# 关闭或显示选项界面
func display_options_screen():
	if options_screen:
		close_options_screen()
		return
	options_screen = PREFAB_OPTIONS_SCREEN.instantiate() as OptionsScreen
	options_screen.input_manager = inputManager
	options_screen.accept.connect(on_options_screen_accept)
	add_child(options_screen)
	StageManager.screen_ui_display.emit(Screen.OPTIONS_SCREEN, true)
	StageManager.stage_pause(true)



# 显示死亡界面
func display_death_screen():
	if death_screen:
		return
	death_screen = PREFAB_DEATH_SCREEN.instantiate() as DeathScreen
	death_screen.timeout.connect(on_death_screen_timeout)
	add_child(death_screen)
	StageManager.screen_ui_display.emit(Screen.DEATH_SCREEN, true)
	# 延迟暂停，为了执行角色的完死亡动画
	StageManager.stage_pause(true, 2.5)



func display_game_over_screen():
	if game_over_screen:
		return
	game_over_screen = PREFAB_GAME_OVER_SCREEN.instantiate() as GameOverScreen
	game_over_screen.set_score(scoreIndicator.current_score)
	add_child(game_over_screen)
	StageManager.screen_ui_display.emit(Screen.GAME_OVER_SCREEN, true)



# 选项界面点击返回时
func on_options_screen_accept():
	close_options_screen()


# 死亡倒计时结束时，显示游戏结束
func on_death_screen_timeout():
	if death_screen:
		close_death_screen()
	display_game_over_screen()


func close_options_screen():
	options_screen.queue_free()
	options_screen = null
	StageManager.screen_ui_display.emit(Screen.OPTIONS_SCREEN, false)
	StageManager.stage_pause(false)


func close_death_screen():
	death_screen.queue_free()
	death_screen = null
	StageManager.screen_ui_display.emit(Screen.DEATH_SCREEN, false)



# 更新显示玩家头像生命值
func on_player_health_change(current_health: int, max_health: int):
	playerHealthBar.refresh(current_health, max_health)



func update_enemy_avatar(delta: float):
	if enemy_avatar_hide_time < 0.0:
		enemyAvatar.visible = false
		return
	enemy_avatar_hide_time -= delta



# 更新显示敌人头像生命值
func on_enemy_health_change(type: EnemyData.EnemyType, current_health: int, max_health: int):
	var value: Variant = TEXTURE_AVATAR_MAP.get(type)
	if value:
		enemyAvatar.texture = value as CompressedTexture2D
		enemyAvatar.visible = true
	enemyHealthBar.refresh(current_health, max_health)
	enemy_avatar_hide_time = duration_enemy_avatar_hide



# 更新显示连击提示
func on_combo_reset(points: int):
	scoreIndicator.add_combo(points)



# 完成检查点，显示 go 图标提示
func on_checkpoint_complete(_checkpoint: Checkpoint):
	goIndicator.start_flickering()


# 玩家死亡，显示死亡面板
func on_player_dead():
	display_death_screen()


# 是否有足够分数重生
func can_reborn() -> bool:
	return scoreIndicator.current_score >= reborn_cost_score


# 扣除分数，玩家重生
func player_reborn():
	scoreIndicator.set_score(scoreIndicator.current_score - reborn_cost_score)
	StageManager.stage_pause(false)
	StageManager.reborn_player()
